
package com.liao.badminton.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.liao.badminton.code.PageParam;
import com.liao.badminton.code.ProjectException;
import com.liao.badminton.code.RespCodeMessage;
import com.liao.badminton.code.ResponseRest;
import com.liao.badminton.code.util.CheckUtil;
import com.liao.badminton.code.validation.Delete;
import com.liao.badminton.code.validation.FindDetail;
import com.liao.badminton.code.validation.Insert;
import com.liao.badminton.code.validation.Update;
import com.liao.badminton.dto.ImportRecordDto;
import com.liao.badminton.service.ImportRecordService;
import com.liao.badminton.vo.BoutStatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author liaocheng
 * @date 2024-11-01
 * description:录入记录表:修改录入的时候要删掉单局和统计记录
 */
@RestController
@RequestMapping(value = "/importRecord")
// @PreAuthorize("@ss.hasPermission('importRecord')")//权限管理;
public class ImportRecordController {

    //  private static  Logger logger= LoggerFactory.getLogger(ImportRecordController.class);

    @Autowired
    private ImportRecordService importRecordService;

    /**
     * 新增importRecord
     */
    @RequestMapping(value = "/add")
//    @PreAuthorize("@ss.hasPermission('importRecord:add')")//权限管理;
    @Transactional(propagation = Propagation.REQUIRED, timeout = 10000, rollbackFor = Exception.class)
    public ResponseRest<List<BoutStatVo>> add(@RequestBody @Validated(Insert.class) ImportRecordDto importRecord) throws ProjectException {
        return importRecordService.saveImportRecord(importRecord);
    }
    /**
     * 下载录入模板文件
     */
    @GetMapping("/download")
    @PreAuthorize("@ss.hasPermission('file/download')")
    public void download(HttpServletResponse response){
        Set< Map<String,Object>> headers = new HashSet<>();
        TreeMap<String,Object> list = new TreeMap<>();
        list.put("对战记录不能为空",null);
        list.put("群id",null);
        list.put("对战时间",null);
        list.put("是否加入统计：0否，1是",null);
        headers.add(list);
        OutputStream out = null;
        try (ExcelWriter writer = ExcelUtil.getWriter()) {
            writer.write(headers, true);// 写入数据
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("对局模板.xlsx", "UTF-8"));
            out = response.getOutputStream();// 获取流
            writer.flush(out, true); // 将数据流输出到文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        IoUtil.close(out);// 流的操作要关闭
    }
    /**
     * 上传文件录入
     *
     * @param file
     * @param groupId
     * @return
     */
    @PostMapping( "/upload")
    @PreAuthorize("@ss.hasPermission('importRecord:upload')")
    @Transactional
    public ResponseRest<List<BoutStatVo>> upload(@RequestPart("files") MultipartFile file,
                                                  @RequestParam(name = "groupId",required = false) Long groupId,
                                                  @RequestParam(name = "validStatus",required = false) Integer validStatus) {
        if (!file.isEmpty()) {
            try {
                String name = file.getOriginalFilename();
                assert name != null;
                Boolean isXlsx = name.endsWith(".xlsx") || name.endsWith(".xls");
                Boolean isTxt = name.endsWith(".txt");
                StringBuilder sb = new StringBuilder();
                if (isTxt) {
                    InputStreamReader inputStreamReader = new InputStreamReader(file.getInputStream(), "UTF-8");     // 解决中文乱码问题
                    BufferedReader reader = new BufferedReader(inputStreamReader);
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line).append("\n");
                    }
                    ImportRecordDto importRecord = new ImportRecordDto();
                    importRecord.setGroupId(groupId);
                    importRecord.setTxtContent(sb.toString());
                    return importRecordService.saveImportRecord(importRecord);
                } else if (isXlsx) {
                    ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
//                    List<ImportRecordDto> list = reader.readAll(ImportRecordDto.class);
                    List<List<Object>> list = reader.read(1);

                    List<Map<String,Object>> readAll = reader.readAll();
                    for (Map<String,Object> row : readAll) {
                        //key值查看下载模样：com.liao.badminton.controller.FileDealController.download
                        Object o = row.get("对战记录不能为空");
                        CheckUtil.checkValue(o, "对战记录不能为空");
                        ImportRecordDto importRecord = new ImportRecordDto();
                        importRecord.setTxtContent(o.toString());
                        importRecord.setGroupId(row.get("群id") == null ? null : Long.parseLong(row.get("群id").toString()));
                        importRecord.setCreateTime(row.get("对战时间") == null ? null : DateUtil.parse(row.get("对战时间").toString()));
                        importRecord.setValidStatus(row.get("是否加入统计：0否，1是") == null ? null : Integer.parseInt(row.get("是否加入统计：0否，1是").toString()));
                        if (ObjectUtil.isEmpty(importRecord.getGroupId())) {
                            importRecord.setGroupId(groupId);
                        }
                        if (ObjectUtil.isEmpty(importRecord.getValidStatus())) {
                            importRecord.setValidStatus(validStatus);
                        }
                        importRecordService.saveImportRecord(importRecord);
                    }

//                    for (ImportRecordDto importRecord : list) {
//                        if (ObjectUtil.isEmpty(importRecord.getGroupId())) {
//                            importRecord.setGroupId(groupId);
//                        }
//                        if (ObjectUtil.isEmpty(importRecord.getValidStatus())) {
//                            importRecord.setValidStatus(validStatus);
//                        }
//                        importRecordService.saveImportRecord(importRecord);
//                    }
                    return ResponseRest.suc("upload", "上传成功！！");
                }
            } catch (IOException e) {
                ProjectException.newException(RespCodeMessage.HANDLE_FILE_UPLOAD_ERROR, e.getMessage());
            }
        }
        return ResponseRest.suc("upload", "上传失败！！");
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/deletes")
    @PreAuthorize("@ss.hasPermission('importRecord:deletes')")//权限管理;
    public ResponseRest<Boolean> deletes(@RequestBody @Validated(Delete.class) ImportRecordDto param) throws ProjectException {
        return importRecordService.deletesImportRecord(param);
    }

    /**
     * 修改importRecord
     */
    @RequestMapping(value = "/update")
    @PreAuthorize("@ss.hasPermission('importRecord:update')")//权限管理;
    public ResponseRest<Boolean> update(@RequestBody @Validated(Update.class) ImportRecordDto param) throws ProjectException {
        return importRecordService.updateImportRecord(param);
    }

    @RequestMapping(value = "/findDetail")
    @PreAuthorize("@ss.hasPermission('importRecord:findDetail')")//权限管理;
    public ResponseRest<BoutStatVo> findDetail(@RequestBody @Validated(FindDetail.class) ImportRecordDto param) throws ProjectException {
        return importRecordService.findDetail(param);
    }

    /**
     * 分页查询列表
     */
    @RequestMapping(value = "/list")
    @PreAuthorize("@ss.hasPermission('importRecord:list')")//权限管理;
    public ResponseRest<PageInfo<BoutStatVo>> list(@RequestBody PageParam<ImportRecordDto> body) throws ProjectException {
        return importRecordService.findImportRecordByPageParam(body);
    }

    /**
     * 解析文本
     */
    @RequestMapping(value = "/parseTxt")
    @PreAuthorize("@ss.hasPermission('importRecord:parseTxt')")//权限管理;
    public ResponseRest parseTxt(@RequestParam(name = "parseTxt") String parseTxt,@RequestParam(name = "groupId")Long groupId) throws ProjectException{
        return importRecordService.parseTxt(parseTxt, groupId);
    }

}
